# coding:utf-8
from PyFilesDownloader.Qt import M3u8DownloaderThread
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QWidget, QFileDialog, QHBoxLayout
from qfluentwidgets import GroupHeaderCardWidget, LineEdit, FluentIcon as FIF, PushButton, SpinBox, PrimaryPushButton, \
    InfoBar, Slider, BodyLabel

from common import AppPluginBase, SingleIcon, cfg
from components import BaseScrollArea


class SliderWidget(QWidget):
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.slider = Slider(self)
        self.label = BodyLabel(self)
        self.hBox = QHBoxLayout(self)

        self.slider.setRange(1, 20)
        self.slider.setOrientation(Qt.Orientation.Horizontal)
        self.slider.valueChanged.connect(self.onValueChanged)

        self.hBox.addWidget(self.slider)
        self.hBox.addWidget(self.label)

    def onValueChanged(self, value: int):
        self.label.setText(str(value))

    def value(self):
        return self.slider.value()

    def setValue(self, value: int):
        self.slider.setValue(value)
        self.label.setText(str(value))


class M3U8DownView(BaseScrollArea):
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.save_path = ''
        self.downThread = M3u8DownloaderThread(self)
        self.groupHeader = GroupHeaderCardWidget('M3U8下载器', self)

        self.urlEdit = LineEdit(self)
        self.filenameEdit = LineEdit(self)
        self.saveBtn = PushButton(FIF.SAVE, '保存', self)
        self.semaphoreSlider = SliderWidget(self)
        self.retrySpin = SpinBox(self)
        self.startBtn = PrimaryPushButton(FIF.PLAY, '开始', self)

        self.setReturnVisible(True)
        self.urlEdit.setClearButtonEnabled(True)
        self.urlEdit.setPlaceholderText('请输入M3U8地址')
        self.filenameEdit.setClearButtonEnabled(True)
        self.filenameEdit.setPlaceholderText('请输入文件名')
        self.retrySpin.setRange(1, 10)
        self.retrySpin.setValue(7)
        self.retrySpin.setSuffix('次')
        self.semaphoreSlider.setValue(5)

        self.groupHeader.addGroup(
            FIF.LINK, 'M3U8地址', '请输入M3U8地址', self.urlEdit, stretch=1
        )
        self.groupHeader.addGroup(
            FIF.DOCUMENT, '文件名', '请输入文件名, 不输入后缀, 默认为 mp4',
            self.filenameEdit, stretch=1
        )
        self.saveGroup = self.groupHeader.addGroup(
            FIF.FOLDER, '保存路径', '请选择保存路径', self.saveBtn, stretch=0
        )
        self.groupHeader.addGroup(
            FIF.LINK, '重试次数', '设置重试次数', self.retrySpin, stretch=0
        )
        self.groupHeader.addGroup(
            FIF.LINK, '并发数', '设置并发数', self.semaphoreSlider, stretch=1
        )
        self.groupHeader.addGroup(
            FIF.PLAY, '开始下载', '开始下载', self.startBtn, stretch=0
        )

        self.scrollLayout.addWidget(self.groupHeader)
        self.saveBtn.clicked.connect(self.__onSaveBtnClicked)
        self.startBtn.clicked.connect(self.download)
        self.downThread.started.connect(self.__onThreadStarted)
        self.downThread.logSignal.connect(self.setDialogContent)
        self.downThread.finished.connect(self.__onThreadFinished)

    def __onSaveBtnClicked(self):
        path = QFileDialog.getExistingDirectory(self, '选择保存路径', '')
        if path:
            self.save_path = path
            self.saveGroup.setContent('保存路径: ' + path)

    def download(self):
        url = self.urlEdit.text()
        if not url.startswith('http') and not url.endswith('.m3u8'):
            return
        if not self.save_path:
            return
        if not self.filenameEdit.text():
            return
        self.downThread.setParams(
            url, self.save_path,
            self.filenameEdit.text() + '.mp4',
            retry=self.retrySpin.value(),
            merge_mode='ffmpeg',
            ffmpeg_path=cfg.ffmpegFolder.value,
            semaphore=self.semaphoreSlider.value()
        )
        self.downThread.start()

    def __onThreadStarted(self):
        self._showLoading()
        self.setDialogContent(f'开始下载: {self.filenameEdit.text()}')

    def __onThreadFinished(self):
        self._showLoading()
        InfoBar.success('下载成功', '文件已保存到' + self.save_path, duration=3000, parent=self)


class Plugin(AppPluginBase):
    icon = SingleIcon.M3U8

    def __init__(self, iface):
        super().__init__(iface)
        self.subWidget = M3U8DownView(self.iface)
        self.setSubWidgt(self.subWidget)
